<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-01 10:07:47
 * @LastEditTime: 2024-02-04 13:12:02
-->
<script lang="ts" setup name="ManageDepartment">
import type { ElTree } from 'element-plus'
import { ikTree } from 'iking-utils'
import type { Ref } from 'vue'
import type { FilterNodeMethodFunction, TreeNodeData } from 'element-plus/es/components/tree/src/tree.type'
import DepModal from './DepModal.vue'
import DepTable from './DepTable.vue'
import { depApi } from '@/MainApp/apis/dep'
import { userApi } from '@/MainApp/apis/user'
import { systemConfig } from '@/system.config'
// 启用组织
const ENABLE_ORGANIZA = systemConfig.organiza?.enable

const { t } = useConfig()
const { msgSuccess, msgError, msgBoxWarnAsync } = useMessage()

const visible = ref(false)
const depChange = ref(false)
const depData = ref()
const selectDepNode = ref()
const isEditing = ref(false)
// 新增、修改模态框状态
provide('visible', visible)
// 部门数据更新
provide('depChange', depChange)
// 编辑回显数据
provide('depData', depData)
// 当前选中项
provide('selectDepNode', selectDepNode)

// 新增部门
const handAddDep = () => {
  visible.value = true
  depChange.value = false
  isEditing.value = false
}

// API请求
const loadingTree = ref(false)
watch(
  () => depChange!.value,
  ce => {
    if (ce)
      getAllDeps()
  },
  { deep: true }
)

const defaultExpand: Ref<string[]> = ref([])
const treeRef = ref<{ tree?: InstanceType<typeof ElTree>;filterText: string; }>()
let depList: Array<any> = []
const getAllDeps = async (orgId?: any) => {
  try {
    treeRef.value && (treeRef.value.filterText = '')
  }
  catch (error) {
  }
  loadingTree.value = true
  const { msg, data, success } = await depApi.getAllDeps({ orgId })
  if (success) {
    depList = data
    depData.value = data
      ? ikTree.listToTree(data, { sort: 'sortOrder', needSort: true })
      : []
    !defaultExpand.value.length
      && (defaultExpand.value = depData.value.map((d: { id: string; }) => d.id))
    // 默认选择第一条、并显示第一条下的子单位
    try {
      const firstNode: { id: string; } = depData.value[0]
      selectDepNode.value = firstNode
      nextTick(() => {
        firstNode?.id && treeRef.value?.tree?.setCurrentKey(firstNode.id)
      })
    }
    catch (error) {
      console.info('设置默认选中项错误')
    }
  }
  else { msgError(msg) }

  loadingTree.value = false
}
// 初始获取
getAllDeps()

// 重写过滤方法
const filterNode: FilterNodeMethodFunction = (value: string, data: TreeNodeData) => {
  if (!value)
    return true
  return data.name.includes(value)
}
// 节点展开
const handExpend = (data: { id: string; }) => {
  defaultExpand.value.push(data.id)
}
// 节点关闭
const handCollapse = (data: { id: string; }) => {
  defaultExpand.value.splice(defaultExpand.value.indexOf(data.id), 1)
}
// 选中项
const handleSelectNode = (val: any) => {
  selectDepNode.value = val
}
// 排序
const handSortTree = async (params: any) => {
  const { msg, success } = await depApi.sortTree(params)
  if (success) {
    msgSuccess(msg)
    getAllDeps()
  }
  else { msgError(msg) }
}

const handleDragEnd = (
  oldNode: { data: { sortOrder: any; parentId: any; id: any; }; }, newNode: { data: { sortOrder: any; parentId: any; id: any; }; }, loc: string
) => {
  const params = {
    currentOrder: oldNode.data.sortOrder,
    parentId: oldNode.data.parentId,
    targetOrder: newNode.data.sortOrder,
    targetParentId: newNode.data.parentId,
    position: loc.toUpperCase(),
    currentId: oldNode.data.id,
    targetId: newNode.data.id
  }
  if (depList.length > 1)
    handSortTree(params)
}

// 编辑
const handEditDep = (dep: any) => {
  selectDepNode.value = {
    ...dep,
    managerId: dep.manager ? dep.managerId : ''
  }
  visible.value = true
  isEditing.value = true
}

// 删除
const handRemoveDep = (dep: { id: string; name: string; children: any; }) => {
  msgBoxWarnAsync('确认删除', `删除后，部门【${dep.name}】及其所有的子部门将被一并删除，所有被删除部门下的用户将移动至【${dep.name}】的上级部门。确定删除吗？`, async () => {
    const { msg, success } = await depApi.deleteDep(dep.id)
    if (success) {
      msgSuccess(msg)
      getAllDeps()
    }
    else { msgError(msg) }
  })
}
// 组织数据
const tissueList: any = ref([])
const orgId = ref('')
// 获取组织信息
const organizationData = async () => {
  const { success, msg, data } = await userApi.organizationList()
  if (success) {
    const fixData = [{
      label: '全部',
      value: ''
    },
    ...data?.map((li: { name: any; id: any; }) => {
      return {
        ...li,
        label: li.name,
        value: li.id
      }
    })
    ]
    tissueList.value = fixData
  }
  else {
    tissueList.value = [{
      label: '全部',
      value: ''
    }]
    msgError(msg)
  }
}
const checkNeedOrganization = () => {
  ENABLE_ORGANIZA && organizationData()
}
// checkNeedOrganization()

// 搜索选择组织
const slectChange = async (val: any) => {
  orgId.value = val
  // await queryUser()
  getAllDeps(val)
}

const handRefresh = () => {
  // checkNeedOrganization()

  console.log('handRefresh ')
  getAllDeps()
}
// 新增返回的组织id
const handConfirm = (id: any) => {
  orgId.value = id
  getAllDeps(orgId.value)
}
</script>

<template>
  <IkPageMain fixed>
    <IkSplitPan :size="0" direction="left">
      <template #left>
        <IkPanel
          title="部门列表"
          role="ADD-DEPT"
          @hand-add="handAddDep"
          @hand-refresh="handRefresh"
        >
          <IkTree
            ref="treeRef"
            v-loading="loadingTree"
            :data="depData"
            :props="{ children: 'children', label: 'name' }"
            :highlight-current="true"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            draggable
            node-key="id"
            :default-expanded-keys="defaultExpand"
            @node-click="handleSelectNode"
            @node-drag-end="handleDragEnd"
            @node-expand="handExpend"
            @node-collapse="handCollapse"
          >
            <template #inset>
              <!-- <el-select
                v-if="ENABLE_ORGANIZA"
                v-model="orgId"
                style="width:100%"
                placeholder="请选择组织"
                @change="slectChange"
              >
                <el-option
                  v-for="item in tissueList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select> -->
            </template>
            <template #default="{ data }">
              <div :title="data.name">
                <span class="text-over-line">{{ data.name }}</span>
                <span class="oper-icon">
                  <IkSvgIcon
                    v-role="'UPDATE-DEPT'"
                    show-bg
                    pop
                    :title="t('action.modify')"
                    name="iksvg_bianji"
                    @click.stop="handEditDep(data)"
                  />
                  <IkSvgIcon
                    v-role="'DELETE-DEPT'"
                    show-bg
                    pop
                    :title="t('action.delete')"
                    name="iksvg_shanchu"
                    @click.stop="handRemoveDep(data)"
                  />
                </span>
              </div>
            </template>
          </IkTree>
        </IkPanel>
      </template>
      <template #right>
        <DepTable />
      </template>
    </IkSplitPan>
    <DepModal
      :is-editing="isEditing"
      :select-dep-node="selectDepNode"
      :org-id="orgId"
      @handConfirm="handConfirm"
    />
  </IkPageMain>
</template>

<style lang="scss" scoped>
:deep(.el-tree-node) {
  // margin-bottom: calc(var(--base-m) / 2);
  .el-tree-node__label {
    font-size: var(--el-font-size-medium);
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 1;
  }

  .el-tree-node__content {
    .oper-icon {
      opacity: 0;
      transition: opacity 0.15s ease;

      .ik-bianji {
        color: var(--el-color-primary);
      }

      .ik-shanchu1 {
        color: var(--el-color-danger);
      }
    }

    &:hover {
      .oper-icon {
        opacity: 1;
      }
    }

    // & > .el-tree-node__expand-icon {
    //   font-size: var(--el-font-size-extra-large);
    // }

    & > div{
      display: flex;
      flex: 1;
      justify-content: space-between;
      padding-right: var(--base-padding);
      align-items: center;
      width: calc(100% - 80px);

      & > span{
        display: inline-block;
      }
    }
  }
}
</style>
